package com.yonyou.pmclouds.safetyrectification.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.annotation.Insert;
import com.yonyou.pmclouds.basecom.entity.AdditionalPropertiesVOWrapper;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.IllegalRequestArgException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.service.CommonPropertiesProcessor;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.safetyrectification.acceptrecord.entity.AcceptRecordVO;
import com.yonyou.pmclouds.safetyrectification.assignrecord.entity.AssignRecordVO;
import com.yonyou.pmclouds.safetyrectification.entity.SafetyRectificationVO;
import com.yonyou.pmclouds.safetyrectification.entity.SafetyRectifyFieldConst;
import com.yonyou.pmclouds.safetyrectification.rectificationrecord.entity.RectificationRecordVO;
import com.yonyou.pmclouds.safetyrectification.relationuser.entity.RelationUserVO;
import com.yonyou.pmclouds.safetyrectification.service.ISafetyRectificationMaintain;
import com.yonyou.pmclouds.safetyrectification.service.ISafetyRectificationQuery;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 安全整改控制器
 *
 * @author th
 * @date 2019/10/24 13:37
 */
@RestController
@RequestMapping("/mobile/safetyRectification")
public class SafetyRectificationController {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ISafetyRectificationMaintain maintain;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ISafetyRectificationQuery query;
    @Autowired
    private UserInfoQuery userInfoQuery;
    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;
    @Autowired
    private CommonPropertiesProcessor propertiesProcessor;

    /**
     * 新增
     * @param vo
     * @return
     * @throws BusinessException
     */
    @Insert
    @PostMapping("/add")
    public SafetyRectificationVO add(@RequestBody @Validated SafetyRectificationVO vo,
                                     BindingResult errors) throws BusinessException {
        if (errors.hasErrors())
            throw new IllegalRequestArgException();

        // 先设置用户名称，生成消息通知时使用。设置整改人名称，生成智能日志需要
        vo.setCreator(RuntimeEnvironment.getLoginUserId());
        userInfoQuery.tranUserInfoField(new SafetyRectificationVO[]{vo},
                new String[]{CommonFieldConst.CREATOR, SafetyRectificationVO.PK_RECTIFICATIONER},
                new String[]{CommonFieldConst.CREATOR_NAME, SafetyRectificationVO.RECTIFICATIONER_NAME});

        SafetyRectificationVO resultVO = maintain.add(vo);
        return resultVO;
    }

    /**
     * 交办
     *
     * @param recordVO
     * @return
     * @throws BusinessException
     */
    @PostMapping("/assign")
    public SafetyRectificationVO assign(@RequestBody AssignRecordVO recordVO) throws BusinessException {
        if (StringUtils.isEmpty(recordVO.getAssignUser()) || StringUtils.isEmpty(recordVO.getPkBill()))
            throw new IllegalRequestArgException();

        userInfoQuery.tranUserInfoField(new AssignRecordVO[]{recordVO},
                new String[]{SafetyRectifyFieldConst.SAFETY_RECTIFY_CREATOR, AssignRecordVO.ASSIGN_USER},
                new String[]{SafetyRectifyFieldConst.SAFETY_RECTIFY_CREATOR_NAME, AssignRecordVO.ASSIGN_USER_NAME});

        SafetyRectificationVO resultVO = maintain.assign(recordVO);
        return resultVO;
    }

    /**
     * 整改
     *
     * @param recordVO
     * @return
     * @throws BusinessException
     */
    @PostMapping("/rectify")
    public SafetyRectificationVO rectify(@RequestBody RectificationRecordVO recordVO) throws BusinessException {
        if (StringUtils.isEmpty(recordVO.getPkSafetyRectification()))
            throw new IllegalRequestArgException();

        userInfoQuery.tranUserInfoField(new RectificationRecordVO[]{recordVO},
                new String[]{SafetyRectifyFieldConst.SAFETY_RECTIFY_CREATOR},
                new String[]{SafetyRectifyFieldConst.SAFETY_RECTIFY_CREATOR_NAME});

        SafetyRectificationVO resultVO = maintain.rectify(recordVO);
        return resultVO;
    }

    /**
     * 继续整改
     *
     * @param recordVO
     * @return
     * @throws BusinessException
     */
    @PostMapping("/rectifyAgain")
    public SafetyRectificationVO rectifyAgain(@RequestBody AcceptRecordVO recordVO) throws BusinessException {
        if (StringUtils.isEmpty(recordVO.getPkRectificationRecord()) || StringUtils.isEmpty(recordVO.getPkBill()))
            throw new IllegalRequestArgException();

        userInfoQuery.tranUserInfoField(new AcceptRecordVO[]{recordVO},
                new String[]{SafetyRectifyFieldConst.SAFETY_RECTIFY_CREATOR},
                new String[]{SafetyRectifyFieldConst.SAFETY_RECTIFY_CREATOR_NAME});

        SafetyRectificationVO resultVO = maintain.rectifyAgain(recordVO);
        return resultVO;
    }

    /**
     * 验收通过
     *
     * @param vo
     * @return
     * @throws BusinessException
     */
    @PostMapping("/pass")
    public SafetyRectificationVO pass(@RequestBody SafetyRectificationVO vo) throws BusinessException {
        if (StringUtils.isEmpty(vo.getPkSafetyRectification()))
            throw new IllegalRequestArgException();

        userInfoQuery.tranUserInfoField(new SafetyRectificationVO[]{vo}, new String[]{CommonFieldConst.CREATOR},
                new String[]{CommonFieldConst.CREATOR_NAME});

        SafetyRectificationVO resultVO = maintain.pass(vo);
        return resultVO;
    }

    /**
     * 查询一条安全整改
     *
     * @param id
     * @return
     * @throws BusinessException
     */
    @GetMapping("/queryOne")
    public SafetyRectificationVO queryOne(@RequestParam("id") String id) throws BusinessException {
        SafetyRectificationVO resultVO = query.getById(id);
        List<SafetyRectificationVO> resultList = new ArrayList<>();
        resultList.add(resultVO);
        setUserNameAndConstructUnit(resultList);

        return resultVO;
    }

    @GetMapping("/queryByProject")
    public AdditionalPropertiesVOWrapper[] queryByProject(@RequestParam("pkProject") String pkProject,
                                                          @RequestParam(name = "billStatus", required = false) Integer billStatus) throws BusinessException {
        List<SafetyRectificationVO> safetyRectificationList = query.getByProject(pkProject, billStatus);
        if (CollectionUtils.isEmpty(safetyRectificationList))
            return new AdditionalPropertiesVOWrapper[0];

        setUserNameAndConstructUnit(safetyRectificationList);

        return propertiesProcessor.wrapAdditionalProps(safetyRectificationList.toArray(new SafetyRectificationVO[0]));
    }

    /**
     * 翻译用户id、施工单位
     *
     * @param safetyRectificationList
     */
    private void setUserNameAndConstructUnit(List<SafetyRectificationVO> safetyRectificationList) {
        if (CollectionUtils.isEmpty(safetyRectificationList))
            return;

        // 施工单位翻译
        enterpriseInfoQuery.tranEntInfoField(safetyRectificationList.toArray(new SafetyRectificationVO[0]),
                new String[]{SafetyRectificationVO.PK_CONSTRUCTION_UNIT},
                new String[]{SafetyRectificationVO.CONSTRUCT_UNIT_NAME});

        // 保存要翻译的用户id
        Set<String> userIdSet = new HashSet<>();
        for (SafetyRectificationVO vo : safetyRectificationList) {
            List<AssignRecordVO> assignRecordVOS = vo.getAssignRecordList();
            List<RelationUserVO> relationUserVOS = vo.getRelationUserList();

            // 安全整改，创建人、整改人
            userIdSet.add(vo.getCreator());
            userIdSet.add(vo.getPkRectificationer());

            // 交办记录，交办人
            if (CollectionUtils.isNotEmpty(assignRecordVOS)) {
                for (AssignRecordVO assignVO : assignRecordVOS) {
                    userIdSet.add(assignVO.getAssignUser());
                }
            }

            // 抄送人
            if (CollectionUtils.isNotEmpty(relationUserVOS)) {
                for (RelationUserVO userVO : relationUserVOS) {
                    userIdSet.add(userVO.getRelatedUser());
                }
            }
        }

        // 翻译
        Map<String, String> userMap = userInfoQuery.queryUserNames(userIdSet.toArray(new String[0]));
        if (userMap == null || userMap.size() == 0)
            return;

        // 设置用户名称
        for (SafetyRectificationVO safetyVO : safetyRectificationList) {
            safetyVO.setCreatorName(userMap.get(safetyVO.getCreator()));
            safetyVO.setRectificationerName(userMap.get(safetyVO.getPkRectificationer()));

            List<AssignRecordVO> assignRecordVOS = safetyVO.getAssignRecordList();
            List<RelationUserVO> relationUserVOS = safetyVO.getRelationUserList();
            if (CollectionUtils.isNotEmpty(assignRecordVOS)) {
                for (AssignRecordVO assignVO : assignRecordVOS) {
                    assignVO.setAssignPersonName(userMap.get(assignVO.getAssignUser()));
                }
            }

            List<String> relationUserNameList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(relationUserVOS)) {
                String userName;
                for (RelationUserVO userVO : relationUserVOS) {
                    userName = userMap.get(userVO.getRelatedUser());
                    if (StringUtils.isEmpty(userName)) continue;
                    userVO.setRelatedUserName(userName);
                    relationUserNameList.add(userName);
                }
            }
            safetyVO.setRelationUserNameList(relationUserNameList);
        }
    }

}
